package com.yuncheng.spcyApi.spcy;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.alog.utils.StringEmptyUtils;
import com.yuncheng.spcyApi.bo.JcyJpJcyLbBo;
import com.yuncheng.spcyApi.bo.ParamsBo;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.jcy.JcyPrdjConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.flow.XzswspFlowService;
import com.yuncheng.spcyApi.mapper.SpcyRsHcyMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.spcyService.ZdyUploadFileService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.PageVo;
import com.yuncheng.spcyApi.vo.jcy.JcyJpVo;
import com.yuncheng.spcyApi.vo.jcy.JcyJpdjVo;
import com.yuncheng.spcyApi.vo.jcy.JcyTxUserVo;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import utils.DateConversionUtils;
import utils.ExcelUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hua
 */
@Api(tags = "检查员解聘管理")
@RestController
@RequestMapping("/api/spzx-spcy/jcyjpdj")
public class JcyJpController {

    @Resource
    private ISpcyJcyJprymdService spcyJcyJprymdService;

    @Resource
    private IYcSysUserService sysUserService;

    @Resource
    private SpcyRsHcyMapper spcyRsHcyMapper;

    @Resource
    private ISpcyRsHcyService spcyRsHcyService;

    @Resource
    private ISpcyJcyTxypjpsqService spcyJcyTxypjpsqService;

    @Resource
    private ISpcyRsJcysfbgjlService spcyRsJcysfbgjlService;

    @Resource
    private ISpcyJcyJpjbxxService spcyJcyJpjbxxService;

    @Resource
    private ZdyUploadFileService zdyUploadFileService;

    @Resource
    private XzswspFlowService xzswspFlowService;

    @Log(title = "解聘登记-分页查询")
    @ApiOperation(value = "解聘登记-分页查询")
    @GetMapping(value = "jpdjlbPageList")
    public HttpResult jpdjlbPageList(SpcyJcyJpjbxx query, String gjz, PageVo pageVo, OrderItemVo orderItemVo){

        return HttpResult.ok(spcyJcyJpjbxxService.pageList(query, gjz, pageVo,orderItemVo));
    }

    @Log(title = "解聘登记-新增/保存")
    @ApiOperation(value = "解聘登记-新增/保存")
    @PostMapping(value = "saveJpdj")
    public HttpResult saveJpdj(@RequestBody SpcyJcyJpjbxx bean) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        if (StringEmptyUtils.isBlank(bean.getId())){

            bean = spcyJcyJpjbxxService.addJpjbxx(bean);
        }else {

            spcyJcyJpjbxxService.updateJpjbxx(bean);
        }

        return HttpResultVo.HttpResultSave(bean, "保存成功");
    }

    @Log(title = "解聘登记-删除")
    @ApiOperation(value = "解聘登记-删除")
    @DeleteMapping(value = "deleteJpdj")
    public HttpResult deleteJpdj(@RequestParam(value = "ids",defaultValue = "")String ids){
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("参数为空！");
        }

        List<String> listByIds = StringPatternUtils.getListByIds(ids);

        List<String> tyDelIdList = spcyJcyJpjbxxService.deleteJpjbxx(listByIds);

        // 清空附件
        if (CollectionUtil.isNotEmpty(tyDelIdList)) {
            for (String id : tyDelIdList) {
                // 删除人员名单
                spcyJcyJprymdService.remove(new LambdaQueryWrapper<SpcyJcyJprymd>()
                        .eq(SpcyJcyJprymd::getFjpjbxxid, id));

                List<SpcySqsxWjjl> wjjlList = zdyUploadFileService.queryWjjlByPid(id);
                if (CollectionUtil.isNotEmpty(wjjlList)) {
                    for (SpcySqsxWjjl wjjl : wjjlList) {
                        zdyUploadFileService.deleteFileRecords(wjjl);
                        zdyUploadFileService.deleteFileByUrl(wjjl.getFcflj());
                    }
                }
            }
        }
        return HttpResult.ok("删除成功");
    }

    @Log(title = "解聘登记-提交")
    @ApiOperation(value = "解聘登记-提交")
    @PostMapping(value = "submitJpdj")
    public HttpResult submitJpdj(@RequestBody SpcyJcyJpjbxx bean) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        if (StringUtils.isBlank(bean.getId())){
            return HttpResult.error("参数为空！");
        }

        SpcyJcyJpjbxx jpjbxx = spcyJcyJpjbxxService.getById(bean.getId());
        if (jpjbxx == null){
            return HttpResult.error("没有相匹配的数据！");
        }

        if (StringUtils.isNotBlank(jpjbxx.getFjpzt()) && jpjbxx.getFjpzt().equals(JcyPrdjConstant.JPDJ_JPZT_JPWC)){
            return HttpResult.error("已经提交过了，不要重复提交！");
        }

        // 审批流程是否完成
//        xzswspFlowService.verifyJcyJpInQymdLcIsEnd(bean.getId());

        List<SpcyJcyJprymd> rymdList = spcyJcyJprymdService.list(new LambdaQueryWrapper<SpcyJcyJprymd>()
                .eq(SpcyJcyJprymd::getFjpjbxxid, bean.getId()));
        if (CollectionUtil.isEmpty(rymdList)){
            return HttpResult.error("解聘人员为空！");
        }

        // 提交
        bean.setFjprs(rymdList.size());
        String fjdz = jpjbxx.getFjpfjdz();
        SpcyJcyJpjbxx newJpjbxx = spcyJcyJpjbxxService.submitJpjbxx(jpjbxx, bean);

        // 生成身份变更记录
        newJpjbxx.setFjpfjdz(fjdz);
        syncRySfbgjl(newJpjbxx, rymdList);

        return HttpResult.ok("提交成功");
    }

    @Log(title = "解聘登记人员-分页查询")
    @ApiOperation(value = "解聘登记人员-分页查询")
    @GetMapping(value = "jpdjryPageList")
    public HttpResult jpdjryPageList(SpcyJcyJprymd query, String gjz, PageVo pageVo, OrderItemVo orderItemVo){
        if (StringUtils.isBlank(query.getId())){
            query.setFjpjbxxid("0");
        }else {
            query.setFjpjbxxid(query.getId());
            query.setId("0");
        }
        return HttpResult.ok(spcyJcyJprymdService.pageList(query, gjz, pageVo,orderItemVo));
    }

    @Log(title = "待解聘登记人员-分页查询")
    @ApiOperation(value = "待解聘登记人员-分页查询")
    @GetMapping(value = "jpdjPageList")
    public HttpResult jpdjPageList(SpcyJcyJprymd query, String gjz, PageVo pageVo, OrderItemVo orderItemVo){
        query.setFjpzt(JcyPrdjConstant.JP_JPZT_DJP);
        return HttpResult.ok(spcyJcyJprymdService.pageList(query, gjz, pageVo,orderItemVo));
    }

    @Log(title = "已解聘登记-分页查询")
    @ApiOperation(value = "已解聘登记-分页查询")
    @GetMapping(value = "yjpdjPageList")
    public HttpResult yjpdjPageList(SpcyJcyJprymd query, String gjz, PageVo pageVo, OrderItemVo orderItemVo){
        if (StringEmptyUtils.isBlank(query.getFjpzt())) {
            query.setFjpzt(JcyPrdjConstant.JP_JPZT_YJP);
        }
        return HttpResult.ok(spcyJcyJprymdService.pageList(query, gjz, pageVo,orderItemVo));
    }

    @Log(title = "根据id查询解聘登记")
    @ApiOperation(value = "根据id查询解聘登记")
    @GetMapping(value = "queryJpdjById")
    public HttpResult queryJpdjById(@RequestParam(value = "id",defaultValue = "")String id){
        SpcyJcyJpjbxx jbxx = spcyJcyJpjbxxService.getById(id);

        return HttpResult.ok(jbxx);
    }

    @Log(title = "根据id查询解聘登记人员")
    @ApiOperation(value = "根据id查询解聘登记人员")
    @GetMapping(value = "queryJpdjryById")
    public HttpResult queryJpdjryById(@RequestParam(value = "id",defaultValue = "")String id){
        SpcyJcyJprymd bean = spcyJcyJprymdService.getById(id);

        return HttpResult.ok(bean);
    }

    @Log(title = "获取手动添加人员-分页查询")
    @ApiOperation(value = "获取手动添加人员-分页查询")
    @GetMapping(value = "getSdtjryPageList")
    public HttpResult getSdtjryPageList(YcSysUser query,String gjz, PageVo pageVo){
        return HttpResult.ok(sysUserService.getJpSdtjryPageList(query, gjz, pageVo));
    }

    @Log(title = "解聘登记-手动添加人员")
    @ApiOperation(value = "解聘登记-手动添加人员")
    @PostMapping(value = "sddjRymd")
    public HttpResult sddjRymd(@RequestBody JcyJpdjVo jcyJpdjVo){
        if (StringUtils.isBlank(jcyJpdjVo.getId())){
            return HttpResult.error("参数为空！");
        }
        if (StringUtils.isBlank(jcyJpdjVo.getIds())){
            return HttpResult.error("请选择人员！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(jcyJpdjVo.getIds());
        List<YcSysUser> userList = sysUserService.listByIds(idsList);

        List<SpcyJcyJprymd> newRymdList = new ArrayList<>();
        int nowYear = Integer.valueOf(DateConversionUtils.DateToYear(new Date())); // 当前年份

        if (CollectionUtil.isNotEmpty(userList)) {
            for (YcSysUser user : userList) {

                // 当前用户存在的有效身份
                List<SpcyRsHcy> jcyList = spcyRsHcyService.selectJcyYxList(user.getId());

                int nl = 0;
                String year = DateConversionUtils.getBirghYearFromIdCary(user.getFsfzh());
                if (StringUtils.isNotBlank(year)){
                    nl = nowYear - Integer.valueOf(year);
                }

                JcyJpJcyLbBo userJcyInfo = getUserJcyInfo(jcyList);

                newRymdList.add(initGenRymd(null,user,JcyPrdjConstant.JP_SFZDSCRY_NO, jcyJpdjVo.getId(), nl, userJcyInfo.getJcyids(), userJcyInfo.getJcylb(), userJcyInfo.getFbz()));

            }
        }

        if (CollectionUtil.isNotEmpty(newRymdList)){
            spcyJcyJprymdService.saveBatch(newRymdList);
        }

        return HttpResult.ok("添加成功");
    }

    @Log(title = "解聘登记-生成退休人员名单")
    @ApiOperation(value = "解聘登记-生成退休人员名单")
    @GetMapping(value = "jpdjByScyxrymd")
    public HttpResult jpdjByScyxrymd(SpcyJcyJpjbxx query) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        if (query.getFmaletxnl() == null){
            return HttpResult.error("男职工退休年龄为空！");
        }
        if (query.getFfemaletxnl() == null){
            return HttpResult.error("女职工退休年龄为空！");
        }
        String nowYearStr = DateConversionUtils.DateToYear(new Date());
        int nowYear = Integer.valueOf(nowYearStr);

        // 用当前年份减对应男、女职工的退休年龄得到对应得年份
        String maleYearStr = new BigDecimal(nowYearStr).subtract(new BigDecimal(String.valueOf(query.getFmaletxnl()))).toString();
        String femaleYearStr = new BigDecimal(nowYearStr).subtract(new BigDecimal(String.valueOf(query.getFfemaletxnl()))).toString();

        String nowDate = DateConversionUtils.DateToYYYYMMDD(new Date());

        String mmddStrng = nowDate.substring(4); // 从年月日截取月日
        maleYearStr = maleYearStr+mmddStrng;
        femaleYearStr = femaleYearStr+mmddStrng;

        long maletxnlrq = Long.valueOf(maleYearStr);
        long femaletxnlrq = Long.valueOf(femaleYearStr);

        List<SpcyJcyJprymd> newRymdList = new ArrayList<>();
        // 查询退休用户
        List<JcyTxUserVo> userList = spcyRsHcyMapper.selectTxJcyUserList(nowYear, maletxnlrq, femaletxnlrq);

        // 删除待解聘人员
        if (StringUtils.isNotBlank(query.getId())) {
            spcyJcyJpjbxxService.updateJpjbxx(query);
        }

        // 删除
        deleteDjpRymdList(query.getId());

        if (CollectionUtil.isNotEmpty(userList)){
            for (JcyTxUserVo user : userList){

                // 当前用户存在的有效身份
                List<SpcyRsHcy> jcyList = spcyRsHcyService.selectJcyYxList(user.getId());
                JcyJpJcyLbBo userJcyInfo = getUserJcyInfo(jcyList);

                newRymdList.add(initGenRymd(user,null,JcyPrdjConstant.JP_SFZDSCRY_YES, query.getId(), user.getNl(), userJcyInfo.getJcyids(), userJcyInfo.getJcylb(), userJcyInfo.getFbz()));
            }
        }

        if (CollectionUtil.isNotEmpty(newRymdList)){
            spcyJcyJprymdService.saveBatch(newRymdList);
        }

        return HttpResult.ok("生成成功");
    }

    @Log(title = "解聘登记人员-解聘")
    @ApiOperation(value = "解聘登记人员-解聘")
    @PostMapping(value = "jpdjByJp")
    public HttpResult jpdjByJp(@RequestBody JcyJpVo jcyJpVo){
        if (StringEmptyUtils.isBlank(jcyJpVo.getIds())){
            return HttpResult.error("参数为空！");
        }
        if (StringEmptyUtils.isBlank(jcyJpVo.getFjpsj())){
            return HttpResult.error("解聘时间为空！");
        }
        if (StringEmptyUtils.isBlank(jcyJpVo.getFjply())){
            return HttpResult.error("解聘理由为空！");
        }
        List<String> listByIds = StringPatternUtils.getListByIds(jcyJpVo.getIds());
        List<SpcyJcyJprymd> rymdList = spcyJcyJprymdService.listByIds(listByIds);

        /** 解聘人员-身份变更记录 */
        SpcyJcyJpjbxx jcyJpjbxx = new SpcyJcyJpjbxx();
        jcyJpjbxx.setFjpsj(jcyJpVo.getFjpsj());
        jcyJpjbxx.setFjply(jcyJpVo.getFjply());
        jcyJpjbxx.setFjpwh(jcyJpVo.getFjpwh());
        syncRySfbgjl(jcyJpjbxx, rymdList);

        return HttpResult.ok("解聘成功");
    }

    @Log(title = "已解聘登记人员-恢复")
    @ApiOperation(value = "已解聘登记人员-恢复")
    @PostMapping(value = "yjpdjByHf")
    public HttpResult yjpdjByHf(@RequestBody JcyJpVo jcyJpVo){
        if (StringEmptyUtils.isBlank(jcyJpVo.getIds())){
            return HttpResult.error("参数为空！");
        }
        if (StringEmptyUtils.isBlank(jcyJpVo.getFhfsj())){
            return HttpResult.error("恢复时间为空！");
        }
        if (StringEmptyUtils.isBlank(jcyJpVo.getFhfly())){
            return HttpResult.error("恢复理由为空！");
        }
        List<String> listByIds = StringPatternUtils.getListByIds(jcyJpVo.getIds());
        List<SpcyJcyJprymd> rymdList = spcyJcyJprymdService.listByIds(listByIds);

        if (CollectionUtil.isNotEmpty(rymdList)){
            for (SpcyJcyJprymd rymd: rymdList){

                rymd.setFjpzt(JcyPrdjConstant.JP_JPZT_DJP);
                rymd.setFhfsj(jcyJpVo.getFhfsj());
                rymd.setFhfly(jcyJpVo.getFhfly());
                spcyJcyJprymdService.updateById(rymd);

                if (StringUtils.isNotBlank(rymd.getFjpsqid())){
                    updateJpSqInHF(rymd.getFjpsqid(), jcyJpVo.getFhfly());
                }

                // 更新对应的检查员身份状态
                if (StringEmptyUtils.isNotBlank(rymd.getFjcyids())) {
                    List<String> jcyidsList = StringPatternUtils.getListByIds(rymd.getFjcyids());
                    for (String jcyid : jcyidsList) {
                        spcyRsHcyService.updateJcyLbYxState(jcyid);
                    }

                    /** 生成身份变更记录 */
                    spcyRsJcysfbgjlService.initJpJcysgbgjl(rymd.getFuserid(), rymd.getFjcyids(), null, rymd.getFjcyxl(), "","", rymd.getId(),"",true);

                }

                // 更新对应的检查员身份账号的工作状态
                sysUserService.updateUserGzztInZg(rymd.getFuserid());
            }
        }

        return HttpResult.ok("恢复成功");
    }

    @Log(title = "解聘登记人员-删除")
    @ApiOperation(value = "解聘登记人员-删除")
    @DeleteMapping(value = "jpdjBydelete")
    public HttpResult jpdjBydelete(ParamsBo paramsBo){
        if (StringEmptyUtils.isBlank(paramsBo.getIds())){
            return HttpResult.error("参数为空！");
        }

        List<String> idsList = StringPatternUtils.getListByIds(paramsBo.getIds());
        List<SpcyJcyJprymd> rymdList = spcyJcyJprymdService.listByIds(idsList);
        deleteRymdList(rymdList);

        return HttpResult.ok("删除成功");
    }

    @Log(title = "解聘登记人员-导出")
    @ApiOperation(value = "解聘登记人员-导出")
    @ApiImplicitParam(name = "id",value = "解聘登记信息id")
    @GetMapping(value = "exportByJpdj")
    public void exportByJpdj(@RequestParam(value = "id",defaultValue = "")String fjpjbxxid,
                             @RequestParam(value = "ids",defaultValue = "")String ids,
                             @RequestParam(value = "gjz",defaultValue = "")String gjz,
                             HttpServletResponse response){

        String[] titles = new String[]{"序号", "姓名", "性别","身份证号", "工作单位", "年龄","检查员类别", "解聘时间", "解聘理由"};
        List<List<String>> resultList = new ArrayList<>();

        resultList.add(CollectionUtil.newArrayList(titles));

        List<String> dataList = null;

        /*LambdaQueryWrapper<SpcyJcyJprymd> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isBlank(id)){
            queryWrapper.eq(SpcyJcyJprymd::getFjpzt, JcyPrdjConstant.JP_JPZT_DJP);
        }else {
            queryWrapper.eq(SpcyJcyJprymd::getFjpjbxxid, id);
        }
        queryWrapper.orderByDesc(SpcyJcyJprymd::getCreateTime);
        List<SpcyJcyJprymd> userList = spcyJcyJprymdService.list(queryWrapper);*/

        List<SpcyJcyJprymd> userList = spcyJcyJprymdService.selectMdList(fjpjbxxid, gjz, ids);
        for (int order = 0; order < userList.size(); order++){
            dataList = new ArrayList<>();

            dataList.add(String.valueOf(order+1));

            String sex = "";
            if (userList.get(order).getSex() != null){
                if (userList.get(order).getSex().equals(1)){
                    sex = "男";
                }else if (userList.get(order).getSex().equals(2)){
                    sex = "女";
                }
            }

            dataList.add(userList.get(order).getRealname());
            dataList.add(sex);

            dataList.add(userList.get(order).getFsfzh());
            dataList.add(userList.get(order).getFgzdw());

            if (userList.get(order).getFnl() != null) {
                dataList.add(String.valueOf(userList.get(order).getFnl()));
            }else {
                dataList.add("");
            }
            dataList.add(userList.get(order).getFjcyxl());

            dataList.add(userList.get(order).getFjpsj());
            dataList.add(userList.get(order).getFjply());


            resultList.add(dataList);
        }

        // 文件名称
        String title = "人员名单";
        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    @Log(title = "已解聘登记-导出")
    @ApiOperation(value = "已解聘登记-导出")
    @ApiImplicitParam(name = "id",value = "解聘登记信息id")
    @GetMapping(value = "exportByYjpdj")
    public void exportByYjpdj(@RequestParam(value = "id",defaultValue = "")String id, HttpServletResponse response){

        String[] titles = new String[]{"序号", "姓名", "性别","身份证号", "工作单位", "年龄","检查员类别", "解聘时间", "解聘理由"};
        List<List<String>> resultList = new ArrayList<>();

        resultList.add(CollectionUtil.newArrayList(titles));

        List<String> dataList = null;

        LambdaQueryWrapper<SpcyJcyJprymd> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isBlank(id)){
            queryWrapper.eq(SpcyJcyJprymd::getFjpzt, JcyPrdjConstant.JP_JPZT_YJP);
        }else {
            queryWrapper.eq(SpcyJcyJprymd::getFjpjbxxid, id);
        }
        queryWrapper.orderByDesc(SpcyJcyJprymd::getCreateTime);

        List<SpcyJcyJprymd> userList = spcyJcyJprymdService.list(queryWrapper);
        for (int order = 0; order < userList.size(); order++){
            dataList = new ArrayList<>();

            dataList.add(String.valueOf(order+1));

            String sex = "";
            if (userList.get(order).getSex() != null){
                if (userList.get(order).getSex().equals(1)){
                    sex = "男";
                }else if (userList.get(order).getSex().equals(2)){
                    sex = "女";
                }
            }

            dataList.add(userList.get(order).getRealname());
            dataList.add(sex);

            dataList.add(userList.get(order).getFsfzh());
            dataList.add(userList.get(order).getFgzdw());

            if (userList.get(order).getFnl() != null) {
                dataList.add(String.valueOf(userList.get(order).getFnl()));
            }else {
                dataList.add("");
            }
            dataList.add(userList.get(order).getFjcyxl());

            dataList.add(userList.get(order).getFjpsj());
            dataList.add(userList.get(order).getFjply());


            resultList.add(dataList);
        }

        // 文件名称
        String title = "人员名单";
        ExcelUtils.getLocalTitleExcel(resultList,title,response);
    }

    @Log(title = "解聘登记文件-附件上传")
    @ApiOperation(value = "解聘登记文件-附件上传")
    @PostMapping(value = "uploadJpFile")
    public HttpResult<?> uploadJpFile(@RequestParam("file") MultipartFile[] file,
                                        @RequestParam(value = "id",defaultValue = "")String id){
        if (StringEmptyUtils.isBlank(id)){
            return HttpResult.error("参数为空！");
        }

        SpcyJcyJpjbxx jpjbxx = spcyJcyJpjbxxService.getById(id);
        if (jpjbxx == null){
            return HttpResult.error("没有相匹配的数据！");
        }

        List<SpcySqsxWjjl> wjjlList = zdyUploadFileService.queryWjjlByPidNoOrder(id);
        if (CollectionUtil.isNotEmpty(wjjlList)){
            for (SpcySqsxWjjl wjjl : wjjlList) {
                zdyUploadFileService.deleteFileRecords(wjjl);
                zdyUploadFileService.deleteFileByUrl(wjjl.getFcflj());
            }
        }

        String wjid = GetUuIdUtils.ReplaceUuId();
        zdyUploadFileService.uploadFile(file, id, LogConstant.LOGS_JCY_JPDJGL, SpcyConstant.JCY_JPDJ_FILE_BASE_URL+"/"+ DateConversionUtils.DateToYear(new Date()), wjid);

        String wjHttpUrl = zdyUploadFileService.genWjllHttpUrl(wjid);

        jpjbxx.setFjpfjdz(wjHttpUrl);
        spcyJcyJpjbxxService.updateById(jpjbxx);


        return HttpResultVo.HttpResultSave(jpjbxx,"上传成功");
    }

    @Log(title = "批量解聘人员-附件上传")
    @ApiOperation(value = "批量解聘人员-附件上传")
    @PostMapping(value = "uploadBatchFile")
    public HttpResult<?> uploadBatchFile(@RequestParam("file") MultipartFile[] file,
                                      @RequestParam(value = "ids",defaultValue = "")String ids){
        if (StringUtils.isBlank(ids)){
            return HttpResult.error("参数为空！");
        }

        String wjid = GetUuIdUtils.ReplaceUuId();
        zdyUploadFileService.uploadFile(file, wjid, LogConstant.LOGS_JCY_JPDJGL, SpcyConstant.JCY_JPDJ_FILE_BASE_URL+"/"+ DateConversionUtils.DateToYear(new Date()), wjid);
        String wjHttpUrl = zdyUploadFileService.genWjllHttpUrl(wjid);

        List<String> idsList = StringPatternUtils.getListByIds(ids);

        List<SpcyJcyJprymd> rymdList = spcyJcyJprymdService.listByIds(idsList);
        if (CollectionUtil.isNotEmpty(rymdList)) {
            for (SpcyJcyJprymd md : rymdList) {

                deleteRymdFj(md.getFjpfjdz()); // 删除附件地址

                md.setFjpfjdz(wjHttpUrl);
                spcyJcyJprymdService.updateById(md);
            }
        }

        return HttpResultVo.HttpResultSave(wjHttpUrl, "上传成功");
    }

    /**
     * 批量申请解聘人员生成解聘登记
     */
    @Log(title = "批量申请解聘人员生成解聘登记")
    @ApiOperation(value = "批量申请解聘人员生成解聘登记")
    @PostMapping(value = "initSqjpToJpdj")
    public HttpResult initSqjpToJpdj(@RequestBody ParamsBo paramsBo){
        if (StringUtils.isBlank(paramsBo.getIds())){
            return HttpResult.error("参数为空！");
        }

        List<SpcyJcyTxypjpsq> sqList = spcyJcyTxypjpsqService.listByIds(StringPatternUtils.getListByIds(paramsBo.getIds()));

        List<SpcyJcyTxypjpsq> jpsqList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(sqList)){
            jpsqList = sqList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFsqlx())
                            && f.getFsqlx().equals(SpcyCommonConstant.TXYPJP_SQLX_JP)
                            && StringUtils.isNotBlank(f.getFshzt())
                            && f.getFshzt().equals(SpcyCommonConstant.TXYPJP_SQ_SHZT_WSH))
                    .collect(Collectors.toList());
        }

        if (CollectionUtil.isEmpty(jpsqList)){
            return HttpResult.ok("没有符合的数据！");
        }

        SpcyJcyJpjbxx bean = new SpcyJcyJpjbxx();
        bean.setId(GetUuIdUtils.ReplaceUuId());
        bean.setFjprs(jpsqList.size());
        spcyJcyJpjbxxService.addJpjbxx(bean);

        List<SpcyJcyJprymd> newRymdList = new ArrayList<>();
        int nowYear = Integer.valueOf(DateConversionUtils.DateToYear(new Date())); // 当前年份
        for (SpcyJcyTxypjpsq sq : jpsqList){

            YcSysUser user = sysUserService.getById(sq.getFuserid());
            if (user == null){
                continue;
            }

            // 申请解聘的类别
            List<SpcyRsHcy> jcyList = spcyRsHcyService.list(new LambdaQueryWrapper<SpcyRsHcy>()
                    .eq(SpcyRsHcy::getFuserid, sq.getFuserid())
                    .in(SpcyRsHcy::getFlx, StringPatternUtils.getListByIds(sq.getFsqjcylb())));

            JcyJpJcyLbBo userJcyInfo = getUserJcyInfo(jcyList);

            int nl = 0;
            String year = DateConversionUtils.getBirghYearFromIdCary(user.getFsfzh());
            if (StringUtils.isNotBlank(year)){
                nl = nowYear - Integer.valueOf(year);
            }

            newRymdList.add(initGenRymd(null,user,JcyPrdjConstant.JP_SFZDSCRY_NO, bean.getId(), nl, userJcyInfo.getJcyids(), userJcyInfo.getJcylb(), userJcyInfo.getFbz(), sq.getId(), sq.getFsqyy()));

            sq.setFsfycl(SpcyCommonConstant.TXYPJP_SQ_SFYCL_YES);
            spcyJcyTxypjpsqService.updateById(sq);
        }

        if (CollectionUtil.isNotEmpty(newRymdList)){
            spcyJcyJprymdService.saveBatch(newRymdList);
        }

        return HttpResult.ok("批量生成解聘登记成功");
    }

    /**
     * 初始化生成人员名单
     * @param sfzdscry 是否自动生成名单
     */
    private SpcyJcyJprymd initGenRymd(JcyTxUserVo txUserVo, YcSysUser user, String sfzdscry, String jpjbxxid, Integer nl, String jcyids, String jcylb, String fbz){
        return initGenRymd(txUserVo, user, sfzdscry, jpjbxxid, nl, jcyids, jcylb, fbz, null, null);
    }


    /**
     * 初始化生成人员名单
     * @param jpsqid 解聘申请id
     * @return
     */
    private SpcyJcyJprymd initGenRymd(JcyTxUserVo txUserVo, YcSysUser user, String sfzdscry, String jpjbxxid, Integer nl, String jcyids, String jcylb, String fbz, String jpsqid, String fsqyy){
        SpcyJcyJprymd jprymd = new SpcyJcyJprymd();

        jprymd.setId(GetUuIdUtils.ReplaceUuId());

        if (user != null){
            jprymd.setFuserid(user.getId());
            jprymd.setSex(user.getSex());
            jprymd.setRealname(user.getRealname());
            jprymd.setFsfzh(user.getFsfzh());
            jprymd.setFgzdw(user.getFgzdw());
        }

        if (txUserVo != null){
            jprymd.setFuserid(txUserVo.getId());
            jprymd.setSex(txUserVo.getSex());
            jprymd.setRealname(txUserVo.getRealname());
            jprymd.setFsfzh(txUserVo.getFsfzh());
            jprymd.setFgzdw(txUserVo.getFgzdw());
        }

        jprymd.setFjpjbxxid(jpjbxxid);
        jprymd.setFnl(nl);

        jprymd.setFjpzt(JcyPrdjConstant.JP_JPZT_DJP);
        jprymd.setFsfzdscry(sfzdscry);
        jprymd.setFjcyids(jcyids);
        jprymd.setFjcyxl(jcylb);

        jprymd.setFjpsqid(jpsqid);

        jprymd.setFbz(fbz);
        jprymd.setFsqyy(fsqyy);
        jprymd.setCreateTime(new Date());
        jprymd.setUpdateTime(new Date());
        jprymd.setCreateBy(GetCurrentUserUtils.getCurrentUserAccount());
        jprymd.setUpdateBy(GetCurrentUserUtils.getCurrentUserAccount());
        jprymd.setSysOrgCode(GetCurrentUserUtils.getCurrentUserOrgCode());

        return jprymd;
    }

    /**
     * 生成对应用户的检查员类别信息
     */
    private JcyJpJcyLbBo getUserJcyInfo(List<SpcyRsHcy> jcyList){
        // 当前用户存在的有效身份
        String jcyids = "";
        String jcylb = "";
        String fbz = "";
        if (CollectionUtil.isNotEmpty(jcyList)){
            for (SpcyRsHcy jcy : jcyList){

                        /*if (StringUtils.isNotBlank(jcylb)
                                && StringUtils.isNotBlank(jcy.getFlx())
                                && jcy.getFlx().equals(JcydjbConstant.LB_YPZCSC)
                                && jcylb.contains(JcydjbConstant.LB_YPZCSC)) {
                        }else {*/
                if (StringEmptyUtils.isBlank(jcyids)) {
                    jcyids += jcy.getId();
                    jcylb += jcy.getFjcyxl();
                } else {
                    jcyids += "," + jcy.getId();
                    jcylb += "," + jcy.getFjcyxl();
                }

                if (StringUtils.isNotBlank(jcy.getFypjssj())) {
                    int flag = jcy.getFypjssj().compareTo(DateConversionUtils.DateToStringYYYYMMDD(new Date()));
                    if (flag > 0) {
                        if (StringUtils.isBlank(fbz)) {
                            fbz += jcy.getFjcyxl() + "聘任至-" + jcy.getFypjssj();
                        } else {
                            fbz += "、" + jcy.getFjcyxl() + "聘任至-" + jcy.getFypjssj();
                        }
                    }
                }
            }
        }

        return new JcyJpJcyLbBo(jcyids, jcylb, fbz);
    }

    /**
     * 删除待解聘的人员名单
     */
    private void deleteDjpRymdList(String fjpjbxxid){
        if (StringUtils.isBlank(fjpjbxxid)) {
            List<SpcyJcyJprymd> rymdList = spcyJcyJprymdService.list(new LambdaQueryWrapper<SpcyJcyJprymd>()
                    .eq(SpcyJcyJprymd::getFjpzt, JcyPrdjConstant.JP_JPZT_DJP)
                    .isNull(SpcyJcyJprymd::getFjpjbxxid));
            deleteRymdList(rymdList);
        }else {
            spcyJcyJprymdService.remove(new LambdaQueryWrapper<SpcyJcyJprymd>()
                    .eq(SpcyJcyJprymd::getFjpjbxxid, fjpjbxxid)
                    .eq(SpcyJcyJprymd::getFjpzt, JcyPrdjConstant.JP_JPZT_DJP)
                    .isNull(SpcyJcyJprymd::getFjpsqid));
        }

    }

    /**
     * 删除待解聘的人员名单
     */
    private void deleteRymdList(List<SpcyJcyJprymd> rymdList){
        if (CollectionUtil.isEmpty(rymdList)){
            return;
        }else {
            for (SpcyJcyJprymd md : rymdList){
                deleteRymdFj(md.getFjpfjdz()); // 删除附件地址

                spcyJcyJprymdService.removeById(md.getId());

                if (StringUtils.isNotBlank(md.getFjpsqid())){
                    cancelJpsqInClzt(md.getFjpsqid());
                }
            }
        }
    }

    /**
     * 删除人员相关附件
     * @param fjpfjdz
     */
    private void deleteRymdFj(String fjpfjdz){
        // 附件是否存在,存在数量为1 删除
        if (StringUtils.isNotBlank(fjpfjdz)) {
            List<SpcyJcyJprymd> fjRyList = spcyJcyJprymdService.list(new LambdaQueryWrapper<SpcyJcyJprymd>()
                    .eq(SpcyJcyJprymd::getFjpfjdz, fjpfjdz));
            if (CollectionUtil.isNotEmpty(fjRyList) && fjRyList.size() == 1) {
                String oldWjid = "";
                String[] split = fjpfjdz.split("id=");
                if (split.length > 1) {
                    oldWjid = split[1];
                }

                List<SpcySqsxWjjl> wjjlList = zdyUploadFileService.queryWjjlByPidNoOrder(oldWjid);
                if (CollectionUtil.isNotEmpty(wjjlList)) {
                    for (SpcySqsxWjjl wjjl : wjjlList) {
                        zdyUploadFileService.deleteFileRecords(wjjl);
                        zdyUploadFileService.deleteFileByUrl(wjjl.getFcflj());
                    }
                }
            }
        }
    }

    /**
     * 解聘人员-身份变更记录
     */
    private void syncRySfbgjl(SpcyJcyJpjbxx query, List<SpcyJcyJprymd> rymdList){
        if (CollectionUtil.isEmpty(rymdList)){
            return;
        }else {
            for (SpcyJcyJprymd rymd : rymdList) {

                rymd.setFjpzt(JcyPrdjConstant.JP_JPZT_YJP);
                rymd.setFjpsj(query.getFjpsj());
                rymd.setFjply(query.getFjply());
                rymd.setFjpwh(query.getFjpwh());
                if (StringUtils.isNotBlank(query.getFjpfjdz())) {
                    rymd.setFjpfjdz(query.getFjpfjdz());
                }

                if (StringUtils.isNotBlank(rymd.getFjpsqid())){
                    updateJpSqInShtg(rymd.getFjpsqid());
                }
                spcyJcyJprymdService.updateById(rymd);

                // 更新对应的检查员身份状态
                if (StringEmptyUtils.isNotBlank(rymd.getFjcyids())) {
                    List<String> jcyidsList = StringPatternUtils.getListByIds(rymd.getFjcyids());
                    for (String jcyid : jcyidsList) {
                        spcyRsHcyService.updateJcyLbWxState(jcyid);
                    }

                    /** 生成身份变更记录 */
                    spcyRsJcysfbgjlService.initJpJcysgbgjl(rymd.getFuserid(), rymd.getFjcyids(), null, rymd.getFjcyxl(), "", "", rymd.getId(), rymd.getFjpwh(), false);

                }

                // 更新对应的检查员身份账号的工作状态
//                if (StringEmptyUtils.isNotBlank(rymd.getFsfzdscry()) && rymd.getFsfzdscry().equals(JcyPrdjConstant.JP_SFZDSCRY_YES))
//                }

                if (StringUtils.isBlank(rymd.getFjpsqid())) {
                    sysUserService.updateUserGzztInJp(rymd.getFuserid());
                }else {
                    // 是否存在有效的身份，不存在解聘
                    List<SpcyRsHcy> yxJcyList = spcyRsHcyService.selectJcyYxList(rymd.getFuserid());
                    if (CollectionUtil.isEmpty(yxJcyList)){
                        sysUserService.updateUserGzztInJp(rymd.getFuserid());
                    }
                }
            }
        }
    }

    /** 更新解聘申请-审核通过 */
    private void updateJpSqInShtg(String jpsqid){
        LambdaUpdateWrapper<SpcyJcyTxypjpsq> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcyJcyTxypjpsq::getId, jpsqid);

        SpcyJcyTxypjpsq update = new SpcyJcyTxypjpsq();
        update.setFshzt(SpcyCommonConstant.TXYPJP_SQ_SHZT_YSH);
        update.setFsftysq(SpcyCommonConstant.TXYPJP_SQ_SFTYSQ_YES);
        update.setFblyj("同意。");
        spcyJcyTxypjpsqService.update(update, updateWrapper);
    }

    /** 更新解聘申请-驳回恢复 */
    private void updateJpSqInHF(String jpsqid, String blyj){
        /*LambdaUpdateWrapper<SpcyJcyTxypjpsq> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcyJcyTxypjpsq::getId, jpsqid);

        SpcyJcyTxypjpsq update = new SpcyJcyTxypjpsq();
        update.setFsftysq(SpcyCommonConstant.TXYPJP_SQ_SFTYBQ_NO);
        update.setFblyj(blyj);
        spcyJcyTxypjpsqService.update(update, updateWrapper);*/
    }

    /** 更新解聘申请-取消处理状态 */
    private void cancelJpsqInClzt(String jpsqid){
        LambdaUpdateWrapper<SpcyJcyTxypjpsq> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcyJcyTxypjpsq::getId, jpsqid);

        SpcyJcyTxypjpsq updateSq = new SpcyJcyTxypjpsq();
        updateSq.setFsfycl(SpcyCommonConstant.TXYPJP_SQ_SFYCL_NO);
        spcyJcyTxypjpsqService.update(updateSq, updateWrapper);
    }
}
